import hljs from "highlight.js/lib/core"
import javascript from "highlight.js/lib/languages/javascript"
import typescript from "highlight.js/lib/languages/typescript"
import python from "highlight.js/lib/languages/python"
import java from "highlight.js/lib/languages/java"
import cpp from "highlight.js/lib/languages/cpp"
import csharp from "highlight.js/lib/languages/csharp"
import php from "highlight.js/lib/languages/php"
import go from "highlight.js/lib/languages/go"
import rust from "highlight.js/lib/languages/rust"
import sql from "highlight.js/lib/languages/sql"
import bash from "highlight.js/lib/languages/bash"
import json from "highlight.js/lib/languages/json"
import xml from "highlight.js/lib/languages/xml"
import css from "highlight.js/lib/languages/css"

// 注册常用语言
hljs.registerLanguage("javascript", javascript)
hljs.registerLanguage("typescript", typescript)
hljs.registerLanguage("python", python)
hljs.registerLanguage("java", java)
hljs.registerLanguage("cpp", cpp)
hljs.registerLanguage("c++", cpp)
hljs.registerLanguage("csharp", csharp)
hljs.registerLanguage("c#", csharp)
hljs.registerLanguage("php", php)
hljs.registerLanguage("go", go)
hljs.registerLanguage("rust", rust)
hljs.registerLanguage("sql", sql)
hljs.registerLanguage("bash", bash)
hljs.registerLanguage("shell", bash)
hljs.registerLanguage("json", json)
hljs.registerLanguage("xml", xml)
hljs.registerLanguage("html", xml)
hljs.registerLanguage("css", css)

import "highlight.js/styles/atom-one-dark.css"

/**
 * 高亮代码块 - 使用自动检测
 */
function highlightCodeBlock(block: HTMLElement) {
  // 如果已经高亮过，跳过
  if ((block as any)._hljs_done) return

  try {
    const code = block.textContent || ''
    // 直接使用自动检测，hljs 会分析代码特征识别语言
    const result = hljs.highlightAuto(code, [
      'javascript', 'typescript', 'python', 'java',
      'cpp', 'csharp', 'php', 'go', 'rust', 'sql', 'bash', 'json', 'xml', 'css'
    ])
    block.innerHTML = result.value
    block.classList.add('hljs')
    // 添加检测到的语言类
    if (result.language) {
      block.classList.add(`language-${result.language}`)
    }
    (block as any)._hljs_done = true
  } catch (err) {
    console.error('代码高亮失败:', err)
  }
}

export const highlight = {
  mounted: (el: any) => {
    const blocks = el.querySelectorAll("pre code")
    blocks.forEach((block: HTMLElement) => {
      highlightCodeBlock(block)
    })
  },
  updated: (el: any) => {
    const blocks = el.querySelectorAll("pre code")
    blocks.forEach((block: HTMLElement) => {
      // 如果已经高亮过，跳过（除非内容变了）
      if ((block as any)._hljs_done) return
      highlightCodeBlock(block)
    })
  }
}
